package com.system.ad.index.keyword;

import com.system.ad.index.IndexAware;
import com.system.ad.utlis.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListSet;

/**
 * 关键字索引
 * 倒排索引，根据关键字查找推广单元，一对多关系
 */
@Slf4j
@Component
public class KeyWordIndex implements IndexAware<String, Set<Long>> {

    // 倒序索引
    private static Map<String, Set<Long>> keywordUnitMap = new ConcurrentHashMap<>();

    // 正序索引
    private static Map<Long, Set<String>> unitKeywordMap = new ConcurrentHashMap<>();


    @Override
    public Set<Long> get(String key) {
        if (StringUtils.isEmpty(key)) {
            return Collections.emptySet();
        }
        // 查找推广单元
        Set<Long> result = keywordUnitMap.get(key);
        if (result == null) {
            return Collections.emptySet();
        }
        return result;
    }

    @Override
    public void add(String key, Set<Long> value) {
        log.info("unitKeywordIndex ,before add:{}", unitKeywordMap);
        // 同时添加到关键字索引和ID索引集合
        // 需要判断key是否存在，创建或直接添加
        Set<Long> unitIdSet = CommonUtils.getterCreate(key, keywordUnitMap, ConcurrentSkipListSet::new);
        unitIdSet.addAll(value);

        // 循环插入推广单元Id
        for (Long unitId : value) {
            Set<String> keywords = CommonUtils.getterCreate(unitId, unitKeywordMap, ConcurrentSkipListSet::new);
            keywords.add(key);
        }
        log.info("unitKeywordIndex ,after add:{}", unitKeywordMap);
    }

    @Override
    public void update(String key, Set<Long> value) {
        log.error("keyword index cat not support update");
    }

    @Override
    public void delete(String key, Set<Long> value) {
        log.info("unitKeywordIndex ,before delete:{}", unitKeywordMap);
        Set<Long> unitIds = CommonUtils.getterCreate(key, keywordUnitMap, ConcurrentSkipListSet::new);
        unitIds.removeAll(value);

        for (Long unitId : value) {
            Set<String> keywords = CommonUtils.getterCreate(unitId, unitKeywordMap, ConcurrentSkipListSet::new);
            keywords.remove(key);
        }
        log.info("unitKeywordIndex ,after delete:{}", unitKeywordMap);
    }


    /**
     * 判断关键字索引是否命中
     *
     * @param unitId
     * @param keywords
     * @return
     */
    public boolean match(Long unitId, List<String> keywords) {
        // 判断索引中是否存在推广单元ID，并且推广关键字不为空
        if (unitKeywordMap.containsKey(unitId) && CollectionUtils.isNotEmpty(unitKeywordMap.get(unitId))) {
            Set<String> unitKeywords = unitKeywordMap.get(unitId);
            //判断关键字是否存在集合中
            return CollectionUtils.isSubCollection(keywords, unitKeywords);
        }
        return false;
    }
}
